package com.realtyManage.springboot.Service.impl;

import com.realtyManage.springboot.Dao.SysJurisdictionRepository;
import com.realtyManage.springboot.Dao.SysUserJurisdictionRepository;
import com.realtyManage.springboot.Dao.UserRepository;
import com.realtyManage.springboot.Model.Do.Jurisdiction;
import com.realtyManage.springboot.Model.Do.User;
import com.realtyManage.springboot.Model.Vo.UserEntity;
import com.realtyManage.springboot.Service.ICustomerService;
import com.realtyManage.springboot.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IUserService userService;

    @Autowired
    private SysJurisdictionRepository sysJurisdictionRepository;

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public User findById(Integer userId) {
        return userRepository.findById(userId).orElse(null);
    }

    @Override
    public User insert(User user) {
        return userRepository.saveAndFlush(user);
    }

    @Override
    public boolean isExistPhone(String phone) {
        User user = userRepository.findByTelephone(phone);
        if(user != null)
            return true;
        else
            return false;
    }

    @Override
    public User getUserByProperty(String phone, String pwd) {
        return userRepository.findByTelephoneAndPwd(phone,pwd);
    }

    @Override
    public User updateUserInfo(User user) {
        return userRepository.saveAndFlush(user);
    }

    @Override
    public Page<User> findPagedByWhereClause(UserEntity userEntity) {
        Integer pageNumber = userEntity.getPageNumber()-1;
        Integer pageSize = userEntity.getPageSize();

        //排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if(userEntity.getSort() != null){
            if (userEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, userEntity.getSortField());
            } else if(userEntity.getSort().equals("ASC")){
                sort = new Sort(Sort.Direction.ASC, userEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber,pageSize,sort);

        //动态查询条件
        Specification<User> specification = (Specification<User>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (userEntity.getLevel()!=null) {
                // 根据角色查询
                Predicate p1 = criteriaBuilder.equal(root.get("level"),userEntity.getLevel());
                list.add(p1);
            }
            if (userEntity.getName()!=null) {
                // 根据姓名查询
                Predicate p2 = criteriaBuilder.like(root.get("name"),"%"+userEntity.getName()+"%" );
                list.add(p2);
            }
            if (userEntity.getUpId()!=null) {
                // 根据上级id查询
                Predicate p3 = criteriaBuilder.equal(root.get("upId"),userEntity.getUpId() );
                list.add(p3);
            }
            if (userEntity.getShopId()!=null) {
                // 根据店铺关联id查询
                Predicate p4 = criteriaBuilder.equal(root.get("connShopId"),userEntity.getShopId() );
                list.add(p4);
            }
            if (userEntity.getStatus()!=null) {
                // 根据客户状态id查询
                Predicate p5 = criteriaBuilder.equal(root.get("status"),userEntity.getStatus() );
                list.add(p5);
            }
            if (userEntity.getPhone()!=null) {
                // 根据手机号查询
                Predicate p5 = criteriaBuilder.equal(root.get("telephone"),userEntity.getPhone() );
                list.add(p5);
            }
            if (userEntity.getUpIds()!=null){
                //Predicate p6 = criteriaBuilder.in(root.get("upId"));
                //list.add(p6);
                Expression<String> exp = root.get("upId");
                list.add(exp.in(userEntity.getUpIds())); // 往in中添加所有id 实现in 查询
            }
            if (userEntity.getShopIds()!=null){
                Expression<String> exp = root.get("connShopId");
                list.add(exp.in(userEntity.getShopIds()));
            }
            if (userEntity.getManageHouseIds()!=null){
                Expression<String> exp = root.get("manageHouseId");
                list.add(exp.in(userEntity.getManageHouseIds()));
            }

            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return userRepository.findAll(specification, pageable);
    }

    @Override
    public User findByTelePhone(String phone) {
        return userRepository.findByTelephone(phone);
    }

    @Override
    public User getInviteUserByCode(String inviteCode, String inviteCode1) {
        List<User> userList = userRepository.findByTelephoneOrInviteCode(inviteCode,inviteCode1);
        if(userList.size()==1){
            return userList.get(0);
        }else if(userList.size()>1){
            System.out.println("查询结果：邀请用户数大于1，请检查邀请码");
            return null;
        }else{
            return null;
        }
    }

    @Override
    public User getSuperAdmin() {
        return userRepository.findByLevelAndStatus(99,1).get(0);
    }

    @Override
    public User getShopManager(int connShopId, int level, int state) {
        return userRepository.findByConnShopIdAndLevelAndStatus(connShopId,level,state);
    }

    @Override
    public int changeShopManager(Integer connShopId, Integer sourceUid) {
        User targetUser = userRepository.findByConnShopIdAndLevelAndStatus(connShopId,4,1);
        //检查待提升用户是否符合条件（没有签约或订购中的客户）
        if(sourceUid != null){
            User sourceUser = userRepository.getOne(sourceUid);
            int count = customerService.countByConnUserIdAndState(sourceUid,3)+customerService.countByConnUserIdAndState(sourceUid,4);
            if(count==0){
                targetUser.setName(sourceUser.getName());
                targetUser.setTelephone(sourceUser.getTelephone());

                //TODO 指定下线接收人

            }else{
                return -51;
            }
        }else{
            targetUser.setName("");
            targetUser.setTelephone("");
        }
        userRepository.saveAndFlush(targetUser);
        return 1;
    }

    @Override
    public List<String> findByNameLike(String upName) {
        return userRepository.findByNameLike(upName);
    }

    @Override
    public List<String> findSpecification(Specification specification) {
        return userRepository.findAll(specification);
    }

    @Override
    public int countByUpIdAndJoinTimeBetween(Integer uid, Date startTime, Date endTime) {
        return userRepository.countByUpIdAndJoinTimeBetween(uid,startTime,endTime);
    }

    @Override
    public List<User> findOneAll(String userId,int condition1) {
        int status = 1; //正常用户
        return userRepository.findOneAll(userId,condition1,status);
    }

    @Override
    public int countCustomerStatus(String userId,String status) {
        return userRepository.countCustomerStatus(userId,status);
    }

    @Override
    public int countUserUpId(String userId) {
        return userRepository.countUserUpId(userId);
    }

    @Override
    public  int setPeriphery(String cd,String id){
        return userRepository.setPeriphery(cd,id);
    }

    @Override
    public String findByName(Integer userId){
        return userRepository.findByName(userId);
    }

    @Override
    public  String findByHouseName(Integer houseId){
        return userRepository.findByHouseName(houseId);
    }

    @Override
    public String findBySex(Integer userId){
        return userRepository.findBySex(userId);
    }

    @Override
    public List<User> findLevelUserList(String level, String type, HttpServletRequest request) {
        if (type.equals("0")){
            level = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getLevel().toString();
            return userRepository.findLevelUserListE(level);
        }else{
            return userRepository.findLevelUserList(level);
        }
    }

    @Override
    public int updatePwd(UserEntity userEntity){
        return userRepository.updatePwd(userEntity);
    }

    @Override
    public String findRegTime(String uid) {
        return userRepository.findRegTime(uid);
    }

    @Override
    public List<User> distributionJurisdictionList() {
        return userRepository.distributionJurisdictionList();
    }

    @Override
    public List<User> queryUserNum() {
        return userRepository.queryUserNum();
    }

    @Override
    public List<String> getRoleUser(String level){
        List ids = new ArrayList();
        String uid[] = level.split(",");
        for (String id : uid){
            ids.add(id);
        }
        return userRepository.getRoleUser(ids);
    }

    @Override
    public List<String> getUserByJurisdiction(String userIds){
        List ids = new ArrayList();
        String uid[] = userIds.split(",");
        for (String id : uid){
            ids.add(id);
        }
        return userRepository.getUserByJurisdiction(ids);
    }


    @Override
    public List<Jurisdiction> getJurisdictionList(){
        return sysJurisdictionRepository.findAll();
    }

    @Override
    public String findQx(String userId){
        return userRepository.findQx(userId);
    }

    @Override
    public int findUserQx(Integer userId, String qx) {
         String arr = userRepository.findUserQx(userId);
         String s[] = arr.split(",");
         for (String kqx : s){
             if (kqx.equals(qx)){
                 return 1;
             }
         }
        return -1;
    }

    @Override
    public int queryUserId(String userName) {
        return userRepository.queryUserId(userName);
    }

    @Override
    public int updateMyDetail(User user) {
        return userRepository.updateMyDetail(user);
    }

    @Override
    public List<User> getReceptionList() {
        return userRepository.getReceptionList();
    }

    @Override
    public int verificationUser(String userName) {
        return userRepository.verificationUser(userName);
    }

    @Override
    public List<User> findNotice() {
        return userRepository.findNotice();
    }

    @Override
    public List<User> findUser() {
        return userRepository.findUser();
    }

    @Override
    public List<String> queryStaff() {
        return userRepository.queryStaff();
    }

    @Override
    public User findLoginName(String phone) {
        return userRepository.findLoginName(phone);
    }


}
